/**
 * userCtrl - AngularJS module for right sidebar.
 *
 *
 * Credits
 * =======
 *
 * Copyright 2015 LonghronShen <LonghronShen@Hotmail.com>
 */


(function() {
    "use strict";

    /**
     * Config
     */
    var moduleName = 'app';
    var DEFAULT_ID = '__default';

    /**
     * Module
     */
    var module;
    try {
        module = angular.module(moduleName);
    } catch (err) {
        // named module does not exist, so create one
        module = angular.module(moduleName, []);
    }

    module.controller('quoteCtrl', ['$scope', '$rootScope', 'i18nService', '$state', '$ngBootbox', 'dataService', 'routeService', 'uiGridConstants', function($scope, $rootScope, i18nService, $state, $ngBootbox, dataService, routeService, uiGridConstants) {
        window.localStorage.id = null;
        window.localStorage.carCode = null;
        // 国际化
        i18nService.setCurrentLang("zh-cn");

        $scope.queryParameter = {
            Keyword: "",
            Carcode: "",
            DriverName: "",
            PhoneNumber: "",
            QuoteStartTime: "",
            QuoteEndTime: "",
            DeliveryAddress: '',
            DestinationAddress: '',
            DeliveryStartTime: "",
            DeliveryEndTime: '',
        }



        var orderBy = $scope.orderBy = "";
        var acs = $scope.acs = 0;
        var skip = $scope.skip = 0;
        var count = $scope.count = 10;

        //角色
        $scope.roles = [];
        var str = [];

        //审核状态枚举

        //初始化列表
        var loadQuotesData = function(queryParameter, orderby, acs, startIndex, count) {
            dataService.getQuoteList(queryParameter.Keyword, queryParameter.Carcode, queryParameter.DriverName, queryParameter.PhoneNumber, queryParameter.QuoteStartTime, queryParameter.QuoteEndTime, queryParameter.DeliveryAddress,
                    queryParameter.DestinationAddress, queryParameter.DeliveryStartTime, queryParameter.DeliveryEndTime, orderby, acs, startIndex, count)
                .then(function(res) {
                    res = res.data || { list: [], total: 0 };
                    // res.Response = res.Response || { Output: { List: [], Total: 0 } };
                    // res.Response.Output = res.Response.Output || { List: [], Total: 0 };
                    // console.info("loadQuotesData: getUsers returned: ", res);
                    var list = res.list;
                    // console.info("loadQuotesData: list: ", list);

                    //$scope.gridApi.grid.options.totalItems = res.result.total;
                    $scope.gridApi.grid.options.totalItems = res.total;

                    // console.info("loadQuotesData: list test1: ", list);
                    $scope.quoteList = { data: list };
                    var currentPage = $scope.gridApi.grid.options.paginationCurrentPage;
                    var totalPages = $scope.gridApi.pagination.getTotalPages();
                    if (totalPages < currentPage) { $scope.gridApi.grid.options.paginationCurrentPage = 1; };
                    $scope.seeks = false;
                }, function(rej) {
                    $ngBootbox.alert(rej);
                    $scope.seeks = false;
                });
        };

        //分页初始化
        var paginationOptions = {
            pageNumber: 0,
            pageSize: 10,
            currentPage: 1,
            sort: null,
            useCache: true,

        };
        var quoteList = $scope.quoteList = {
            data: [],
            paginationPageSizes: [10, 20, 30],
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            columnDefs: [
                { displayName: "报价时间", field: 'quotationTime', type: 'date', cellFilter: 'date:"yyyy-MM-dd HH:mm:ss"', enableColumnMenu: false, enableSorting: true },
                {
                    displayName: "发货地址",
                    field: 'originAddress',
                    enableColumnMenu: false,
                    cellTooltip: true,
                    headerTooltip: true,
                    enableSorting: false
                },
                { displayName: "送货地址", field: 'destinationAddress', enableColumnMenu: false, enableSorting: false },
                { displayName: "发货时间", field: 'deliveryTime', type: 'date', cellFilter: 'date:"yyyy-MM-dd HH:mm:ss"', enableColumnMenu: false, enableSorting: true },
                { displayName: "送货时间", field: 'arrivalTime', type: 'date', cellFilter: 'date:"yyyy-MM-dd HH:mm:ss"', enableColumnMenu: false, enableSorting: true },
                { displayName: "货物类别", field: 'category', enableColumnMenu: false, enableSorting: false },
                //{ displayName: "用户名", field: 'UserName', enableColumnMenu: false },
                { displayName: '货物数量', field: 'amount', enableColumnMenu: false, enableSorting: true },
                { displayName: '所需车长', field: 'carLength', enableColumnMenu: false, enableSorting: false },
                { displayName: '报价人', field: 'quotePerson', enableColumnMenu: false, enableSorting: false },
                { displayName: '报价金额', field: 'price', enableColumnMenu: false, enableSorting: true },
                { displayName: '车牌号', field: 'carCode', enableColumnMenu: false, enableSorting: false },
                { displayName: '手机号', field: 'phoneNumber', enableColumnMenu: false, enableSorting: false },

                {
                    displayName: "操作",
                    field: '操作',
                    cellFilter: 'checkmark',
                    cellTemplate: '<a data-toggle="modal" data-target="#quoteModal" class="fa fa-eye m-l-xs primary text-info" title="查看" ng-click="grid.appScope.checkDetail(row.entity)"></a>',

                    enableColumnMenu: false,
                    enableSorting: false
                }
            ],
            // paginationPageSize: 10,
            onRegisterApi: function(gridApi) {
                $scope.gridApi = gridApi;
                $scope.gridApi.core.on.sortChanged($scope, $scope.sortChanged);
                $scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.OPTIONS);
                //翻页
                gridApi.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
                    paginationOptions.pageNumber = newPage * pageSize - pageSize;
                    paginationOptions.pageSize = pageSize;
                    paginationOptions.currentPage = newPage;
                    $scope.gridApi.grid.options.paginationCurrentPage = newPage;
                    $scope.skip = paginationOptions.pageNumber;
                    $scope.count = paginationOptions.pageSize;
                    loadQuotesData($scope.queryParameter, $scope.orderBy, $scope.acs, paginationOptions.pageNumber, paginationOptions.pageSize);
                    paginationOptions.useCache = true;
                });
            }
        };
        //排序
        $scope.sortChanged = function(grid, sortColumns) {
            if (sortColumns.length === 0) {
                loadQuotesData($scope.queryParameter, $scope.orderBy, $scope.acs, paginationOptions.pageNumber, paginationOptions.pageSize);
            } else {
                switch (sortColumns[0].sort.direction) {
                    case "asc":
                        $scope.orderBy = sortFun(sortColumns[0].name);
                        $scope.acs = 2;
                        loadQuotesData($scope.queryParameter, $scope.orderBy, $scope.acs, paginationOptions.pageNumber, paginationOptions.pageSize);
                        break;
                    case "desc":
                        $scope.orderBy = sortFun(sortColumns[0].name);
                        $scope.acs = 1;
                        loadQuotesData($scope.queryParameter, $scope.orderBy, $scope.acs, paginationOptions.pageNumber, paginationOptions.pageSize);
                        break;
                    case undefined:
                        loadQuotesData($scope.queryParameter, $scope.orderBy, $scope.acs, paginationOptions.pageNumber, paginationOptions.pageSize);
                        break;
                }
            };
        };

        function sortFun(name) {
            switch (name) {
                case 'quotationTime':
                    return 'Time';
                case 'deliveryTime':
                    return 'DeliveryTime';
                case 'arrivalTime':
                    return 'ArrivalTime';
                case 'price':
                    return 'Price';
                case 'amount':
                    return 'Amount';
                default:
                    return name;
            }
        }

        loadQuotesData($scope.queryParameter, $scope.orderBy, $scope.acs, paginationOptions.pageNumber, paginationOptions.pageSize);

        $scope.seeks = false;
        //查询调用
        $scope.queryUsers = function() {

            $scope.seeks = true;
            paginationOptions.pageNumber = 0;
            paginationOptions.currentPage = 1;
            paginationOptions.useCache = false;
            loadQuotesData($scope.queryParameter, $scope.orderBy, $scope.acs, paginationOptions.pageNumber, paginationOptions.pageSize);
        };


        $scope.checkDetail = function(data) {

            $scope.detail = {
                description: data.remark
            }

        };

        $scope.skipExport = function() {
            var url = routeService.Quote.ExportQuoteList.Url;
            window.location.href = routeService.getUrl(url, {
                'KeyWord': $scope.queryParameter.Keyword,
                'CarCode': $scope.queryParameter.Carcode,
                'DriverName': $scope.queryParameter.DriverName,
                'PhoneNumber': $scope.queryParameter.PhoneNumber,
                'QuotationStartTime': $scope.queryParameter.QuoteStartTime,
                'QuotationEndTime': $scope.queryParameter.QuoteEndTime,
                'OriginAddress': $scope.queryParameter.DeliveryAddress,
                'DestinationAddress': $scope.queryParameter.DestinationAddress,
                'DeliveryStartTime': $scope.queryParameter.DeliveryStartTime,
                'DeliveryEndTime': $scope.queryParameter.DeliveryEndTime,
                'orderBy': $scope.orderBy, //
                'acs': $scope.acs,
                'startIndex': paginationOptions.pageNumber,
                'count': paginationOptions.pageSize

            });
        }


    }]);
})();